<template>
  <div class="department-management-page">
    <!-- 标题与操作 -->
    <div class="header-row">
      <h1 class="page-title">科室管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showAddDialog">新增科室</el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <el-card class="filter-card" shadow="hover">
      <el-row :gutter="16" class="row-flex">
        <el-col :xs="24" :sm="8" :md="6">
          <el-input v-model="keyword" placeholder="按科室名称/编码搜索" clearable @keyup.enter="loadData" @clear="loadData">
            <template #append>
              <el-button type="primary" :icon="Search" @click="loadData" /> 
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="deptType" placeholder="科室类型" clearable @change="loadData" style="width:100%">
            <el-option label="门诊" value="门诊" />
            <el-option label="检查" value="检查" />
            <el-option label="检验" value="检验" />
            <el-option label="处置" value="处置" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="8" :md="6">
          <el-select v-model="delmark" placeholder="生效状态" clearable @change="loadData" style="width:100%">
            <el-option label="生效" value="1" />
            <el-option label="未生效" value="0" />
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <!-- 列表 -->
    <el-card class="list-card" shadow="hover">
      <el-table :data="pagedList" stripe :loading="loading" empty-text="暂无数据" style="width:100%">
        <!-- <el-table-column type="selection" width="60" align="center" /> -->
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="deptCode" label="科室编码" width="120" align="center" />
        <el-table-column prop="deptName" label="科室名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="deptType" label="科室类型" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.deptType)" effect="dark" size="small">{{ row.deptType || '未知' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="delmark" label="生效状态" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="row.delmark === 1 ? 'success' : 'danger'" effect="dark" size="small">
              {{ row.delmark === 1 ? '生效' : '未生效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager-wrapper" v-if="filteredList.length > pageSize">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :page-size="pageSize"
          :current-page="pageNum"
          :total="filteredList.length"
          @current-change="(p)=>{pageNum=p}"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="科室编码" prop="deptCode">
          <el-input v-model="formData.deptCode" placeholder="请输入科室编码" />
        </el-form-item>
        <el-form-item label="科室名称" prop="deptName">
          <el-input v-model="formData.deptName" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="科室类型" prop="deptType">
          <el-select v-model="formData.deptType" placeholder="请选择科室类型">
            <el-option label="门诊" value="门诊" />
            <el-option label="检查" value="检查" />
            <el-option label="检验" value="检验" />
            <el-option label="处置" value="处置" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效状态" prop="delmark">
          <el-radio-group v-model="formData.delmark">
            <el-radio :label="1">生效</el-radio>
            <el-radio :label="0">未生效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import * as departmentApi from '@/api/department'

// 状态变量
const loading = ref(false)
const departments = ref([])
const keyword = ref('')
const deptType = ref('')
const delmark = ref('')
const pageNum = ref(1)
const pageSize = ref(10)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增科室')
const editingId = ref(null)
const formRef = ref(null)
const formData = ref({
  deptCode: '',
  deptName: '',
  deptType: '',
  delmark: 1
})

// 表单验证规则
const formRules = {
  deptCode: [
    { required: true, message: '请输入科室编码', trigger: 'blur' },
    { min: 1, max: 20, message: '科室编码长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  deptName: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { min: 1, max: 50, message: '科室名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  deptType: [
    { required: true, message: '请选择科室类型', trigger: 'change' }
  ]
}

// 过滤后的列表
const filteredList = computed(() => {
  return departments.value.filter(item => {
    const matchesKeyword = !keyword.value || 
      item.deptName.toLowerCase().includes(keyword.value.toLowerCase()) ||
      item.deptCode.toLowerCase().includes(keyword.value.toLowerCase())
    const matchesDeptType = !deptType.value || item.deptType === deptType.value
    const matchesDelmark = !delmark.value || String(item.delmark) === delmark.value
    return matchesKeyword && matchesDeptType && matchesDelmark
  })
})

// 分页后的列表
const pagedList = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredList.value.slice(start, end)
})

// 获取科室类型对应的标签类型
const getTagType = (type) => {
  const typeMap = {
    '门诊': 'primary',
    '检查': 'success',
    '检验': 'warning',
    '处置': 'info'
  }
  return typeMap[type] || 'default'
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const response = await departmentApi.getAllDepartments()
    if (response.success && Array.isArray(response.data)) {
      departments.value = response.data
    } else {
      ElMessage.error(response.message || '获取科室列表失败')
    }
  } catch (error) {
    ElMessage.error('获取科室列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增科室'
  editingId.value = null
  formData.value = {
    deptCode: '',
    deptName: '',
    deptType: '',
    delmark: 1
  }
  dialogVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 显示编辑对话框
const showEditDialog = (row) => {
  dialogTitle.value = '编辑科室'
  editingId.value = row.id
  formData.value = { ...row }
  dialogVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    let response
    if (editingId.value) {
      // 编辑
      response = await departmentApi.updateDepartment(editingId.value, formData.value)
    } else {
      // 新增
      response = await departmentApi.addDepartment(formData.value)
    }
    
    if (response.success) {
      ElMessage.success(editingId.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.message || (editingId.value ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    if (error.name === 'Error') {
      // 表单验证错误不需要处理，Element Plus会自动提示
    } else {
      ElMessage.error('操作失败：' + error.message)
    }
  }
}

// 删除科室
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个科室吗？删除后将无法恢复。', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await departmentApi.deleteDepartment(id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    ElMessage.error('删除失败：' + error.message)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  const selectedRows = tableRef.value?.getSelectionRows() || []
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要删除的科室')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.length} 个科室吗？删除后将无法恢复。`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.map(row => row.id)
    const response = await departmentApi.batchDeleteDepartments(ids)
    if (response.success) {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    ElMessage.error('批量删除失败：' + error.message)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.department-management-page {
  padding: 16px;
}

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.filter-card {
  margin-bottom: 16px;
}

.row-flex {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.list-card {
  margin-bottom: 16px;
}

.pager-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>